package com.gitee.shigen.security.filter;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.gitee.shigen.common.msg.Result;
import com.gitee.shigen.security.common.StatusEnum;
import com.gitee.shigen.security.config.JwtConfig;
import com.gitee.shigen.security.service.impl.CustomUserDetailsService;
import com.gitee.shigen.security.util.HttpServletResponseUtil;
import com.gitee.shigen.security.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt拦截器
 *
 * @author shigenfu
 * @date 2024/5/25 17:27
 */
@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private CustomUserDetailsService customUserDetailsService;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private JwtConfig jwtConfig;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        if (checkIgnores(request)) {
            filterChain.doFilter(request, response);
            return;
        }

        String jwt = jwtUtil.getJwtFromRequest(request);

        if (StrUtil.isNotBlank(jwt)) {
            try {
                String username = jwtUtil.getUsernameFromJWT(jwt);

                UserDetails userDetails = customUserDetailsService.loadUserByUsername(username);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(authentication);
                filterChain.doFilter(request, response);
            } catch (SecurityException e) {
                HttpServletResponseUtil.response(response, Result.failed(StatusEnum.TOKEN_PARSE_ERROR.getMessage()));
            }
        } else {
            HttpServletResponseUtil.response(response, new Result(HttpStatus.UNAUTHORIZED.value(), StatusEnum.UNAUTHORIZED.getMessage(), null));
        }

    }

    private boolean checkIgnores(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        return CollectionUtil.contains(jwtConfig.getIgnoreUrl(), requestURI);
    }
}
